﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.Practices.Unity;
using Infrastructure.Web.Extensions;
namespace Infrastructure.Web.WebModules
{
    public class UnityWebModule : IHttpModule
    {
        private HttpApplication context;
        public void Init(HttpApplication context)
        {
            this.context = context;
            this.context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
        }

        public void Dispose() { }

        private void OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            IHttpHandler currentHandler = HttpContext.Current.Handler;
            IUnityContainer container = HttpContext.Current.Application.GetContainer();
            if (currentHandler != null && currentHandler is System.Web.UI.Page)
            {
                var properties = currentHandler.GetType().GetProperties();
                foreach (var item in properties)
                {
                    var dep = Attribute.GetCustomAttribute(item, typeof(Microsoft.Practices.Unity.DependencyAttribute)) as Microsoft.Practices.Unity.DependencyAttribute;
                    if (dep != null)
                    {
                        var value = container.Resolve(item.PropertyType);
                        item.SetValue(currentHandler, value, null);
                    }                    
                }
                
            }
        }
    }
}
